package servlet.other;

import org.apache.commons.dbutils.QueryRunner;
import utils.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//直接删除被举报的文件，并且删除数据库的数据
@WebServlet(name = "DeleteReportedSerevlet", urlPatterns = "/wk07/DeleteReportedSerevlet")
public class DeleteReportedSerevlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        //设置ContentType字段值
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取所要下载的文件Id(数据库删除用)
        int fileId = Integer.parseInt(req.getParameter("fileId"));
        //获取所要下载的文件路径(文件删除用)
        String filePath = req.getParameter("filePath");
        String realPath = getServletContext().getRealPath("/");
        //删除文件
        boolean ok = FileUtils.delete(realPath + filePath);
        //删除成功,自动返回页面
        if (ok) {
            resp.sendRedirect("fileManagement.jsp");
            try {
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai", "root", "123456");
                QueryRunner queryRunner = new QueryRunner();
                //AI编写
                String sql = "delete from file where id=" + fileId;
                //有insert方法可以使用，只不过没有使用
                queryRunner.update(connection, sql);
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {
            writer.println("删除失败!");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
